package com.sky.controller.admin;

import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.Mapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/admin/common")
@Slf4j
@Api(tags = "通用管理")
public class CommonController {
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList(".jpg", ".jpeg", ".png", ".gif");
    @Autowired
    AliOssUtil aliOssUtil;

    //上传图片
    @PostMapping("/upload")
    @ApiOperation(value = "上传图片", tags = "上传图片")
    public Result<String> upload(MultipartFile file) throws IOException {
        log.info("上传图片：{}",file);
        String originalFilename = file.getOriginalFilename();
        // 检查文件名是否为空
        if (originalFilename == null) {return Result.error("上传的文件没有文件名，请检查文件。");}
        // 获取文件扩展名
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 检查扩展名是否合法
        if (!ALLOWED_EXTENSIONS.contains(fileExtension.toLowerCase())) {
            return Result.error("仅支持上传 " + String.join(", ", ALLOWED_EXTENSIONS) + " 格式的图片文件。");
        }
        // 生成新的文件名
        String fileName = UUID.randomUUID().toString() + fileExtension;
        try {
            // 上传文件到阿里云
            String fileUrl = aliOssUtil.upload(file.getBytes(), fileName);
            return Result.success(fileUrl);
        } catch (Exception e) {
            log.error("上传图片失败：{}", e.getMessage());
            return Result.error("上传图片失败：" + e.getMessage());
        }


    }

}
